package com.planw.beetl.findUsages

import com.intellij.core.JavaPsiBundle
import com.intellij.find.impl.HelpID
import com.intellij.ide.TypePresentationService
import com.intellij.java.JavaBundle
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.lang.java.JavaFindUsagesProvider
import com.intellij.psi.*
import com.intellij.psi.impl.search.ThrowSearchUtil
import com.intellij.psi.util.PsiFormatUtil
import com.intellij.psi.util.PsiFormatUtilBase
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ObjectUtils
import com.intellij.util.indexing.IndexingBundle
import com.planw.beetl.utils.JavaService
import org.apache.commons.lang3.StringUtils
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeaderImpl

open class BeetlSqlFindUsagesProvider : FindUsagesProvider {

    companion object {
        val languageIds = setOf<String>("TEXT", "SQL", "Markdown")
        fun findUsagesMapperMethod(element: PsiElement?): List<PsiMethod>? {
            if (element == null || !languageIds.contains(element?.language?.id)) {
                return null;
            }
            val javaService = JavaService.getInstance(element.project)
            val fileName = StringUtils.capitalize(element.containingFile.name.split(".")[0])
            val clazzes = javaService.findMapperClass(fileName);
            if (clazzes == null || clazzes.isEmpty()) {
                return null;
            }
            var headerEl: MarkdownHeaderImpl? = null;
            if (element is MarkdownHeaderImpl) {
                headerEl = element;
            }
            if (headerEl == null) {
                headerEl = PsiTreeUtil.getParentOfType(element, MarkdownHeaderImpl::class.java)
            }
            if (headerEl == null) {
                return null;
            }
            val sqlId = StringUtils.trim(headerEl.getNode().getFirstChildNode().getText())
            if (StringUtils.isBlank(sqlId)) {
                return null;
            }
            val methdStore = javaService.loadMapperPsiMethod(clazzes)
            val methods = methdStore[sqlId]
            return methods
        }
    }

    override fun getNodeText(element: PsiElement, useFullName: Boolean): String {
        return ""
    }

    override fun getDescriptiveName(element: PsiElement): String {
        return ""
    }

    open fun getContainingClassDescription(aClass: PsiClass, formatted: String): String {
        return ""
    }

    override fun getType(element: PsiElement): String {
        return ""
    }

    override fun getHelpId(element: PsiElement): String? {
        return ""
    }

    override fun canFindUsagesFor(psiElement: PsiElement): Boolean {
        val methods = findUsagesMapperMethod(psiElement)
        return  methods != null && methods.isNotEmpty()
    }
}